package com.company.earthquake;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Earthquake extends Activity {
	
	private static final int MENU_UPDATE = Menu.FIRST;
	private static final int MENU_PREFERENCES = Menu.FIRST + 1;	
	private static final int SHOW_PREFERENCES = 1;
	
	ListView earthquakeListView;
	ArrayAdapter<Quake> aa;
	
	ArrayList<Quake> earthquakes = new ArrayList<Quake>();	
	
	EarthquakeReceiver receiver;
	
	private static final int QUAKE_DIALOG = 1;
	
	Quake selectedQuake;
	
	int minimumMagnitude = 0;
	boolean autoUpdate = false;
	int updateFreq = 0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        earthquakeListView = (ListView) findViewById(R.id.earthquakeListView);
        
        aa = new ArrayAdapter<Quake>(this, android.R.layout.simple_expandable_list_item_1, earthquakes);
        
        earthquakeListView.setAdapter(aa);
        
        earthquakeListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				selectedQuake = earthquakes.get(position);
				showDialog(QUAKE_DIALOG);
			}
		});
        
        refreshEarthquakes();
        loadQuakesFromProvider();        
        updateFromPreferences();        
    }
    
    @Override
    protected void onResume() {
    	IntentFilter filter;
    	filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND);
    	receiver = new EarthquakeReceiver();
    	registerReceiver(receiver, filter);
    	
    	loadQuakesFromProvider();
    	super.onResume();
    }
    
    @Override
    protected void onPause() {
    	unregisterReceiver(receiver);
    	super.onPause();
    }
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
    	
    	switch(id){
    	case(QUAKE_DIALOG):
    		SimpleDateFormat sdf;
    		sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    		String dateString = sdf.format(selectedQuake.getDate());
    		String quakeText = "Magnitude" + selectedQuake.getMagnitude() + 
    				"\n" + selectedQuake.getDetails() + "\n" + selectedQuake.getLink();
    		
    		AlertDialog quakeDialog = (AlertDialog) dialog;
    		quakeDialog.setTitle(dateString);
    		
    		TextView tv = (TextView) quakeDialog.findViewById(R.id.quake_detail);
    		tv.setText(quakeText);
    		break;
    	}
    	
    	super.onPrepareDialog(id, dialog);
    }
     
    @Override
    protected Dialog onCreateDialog(int id) {
    	
    	switch(id){
    	case(QUAKE_DIALOG):
    		LayoutInflater li = LayoutInflater.from(this);
    		View quakeDetailsView = li.inflate(R.layout.quake_details, null);
    		
    		AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this);
    		quakeDialog.setTitle("Quake occurrence time");
    		quakeDialog.setView(quakeDetailsView);
    		quakeDialog.setNegativeButton("Close", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
				
				}
			});
    		return quakeDialog.create();
    	}
    	
    	return null;
    }
    
    

	
	
	private void addQuakeToArray(Quake _quake) {
		if(_quake.getMagnitude() > minimumMagnitude){
			earthquakes.add(_quake);
			aa.notifyDataSetChanged();
		}		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		super.onCreateOptionsMenu(menu);		
		menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update);		
		menu.add(0, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		
		switch(item.getItemId()){
		case (MENU_UPDATE):{
			refreshEarthquakes();
			return true;
		}
		case (MENU_PREFERENCES):{
			Intent i = new Intent(this , Preferences.class);
			startActivityForResult(i, SHOW_PREFERENCES);
			return true;
		}
		}
		
		return false; 
	}		
	
	private void refreshEarthquakes() {
		startService(new Intent(this, EarthquakeService.class));
		
	}

	private void updateFromPreferences(){
		SharedPreferences prefs = getSharedPreferences(Preferences.USER_PREFERENCE, Activity.MODE_PRIVATE);
		
		int minMagIndex = prefs.getInt(Preferences.PREF_MIN_MAG, 0);
		if(minMagIndex < 0)
			minMagIndex = 0;
		
		int freqIndex = prefs.getInt(Preferences.PREF_UPDATE_FREQ, 0);
		if(freqIndex < 0)
			freqIndex = 0;
		
		autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);
		
		Resources r = getResources();
		
		int[] minMagValues = r.getIntArray(R.array.magnitude);
		int[] freqValues = r.getIntArray(R.array.update_freq_values);
		
		minimumMagnitude = minMagValues[minMagIndex];
		updateFreq = freqValues[freqIndex];
	}	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == SHOW_PREFERENCES)
			if(resultCode == Activity.RESULT_OK){
				updateFromPreferences();
				refreshEarthquakes();
			}
	}
	
	private void loadQuakesFromProvider(){
		earthquakes.clear();		
		ContentResolver cr = getContentResolver();		
		Cursor c = cr.query(EarthquakeProvider.CONTENT_URI, null, null, null, null);
		
		if(c.moveToFirst()){
			do{
				Long datems = c.getLong(EarthquakeProvider.DATE_COLUMN);
				String details;
				details = c.getString(EarthquakeProvider.DETAILS_COLUMN);
				Float lat = c.getFloat(EarthquakeProvider.LATITUDE_COLUMN);
				Float lon = c.getFloat(EarthquakeProvider.LONGITUDE_COLUMN);
				Double mag = c.getDouble(EarthquakeProvider.MAGNITUDE_COLUMN);
				String link = c.getString(EarthquakeProvider.LINK_COLUMN);
				
				Location location = new Location("dummy");
				location.setLongitude(lon);
				location.setLatitude(lat);
				
				Date date = new Date(datems);
				
				Quake q = new Quake(date, details, location, mag, link);
				addQuakeToArray(q);
			}while(c.moveToNext());
		}
		c.close();
	}
	
	public class EarthquakeReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			loadQuakesFromProvider();
		}
		
	}
}